package com.info.zhiduoduo.wxsdk;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayUtil;
import com.info.zhiduoduo.wxsdk.domain.pay.WxUnifiedOrderData;
import com.info.zhiduoduo.wxsdk.domain.pay.WxUnifiedOrderResult;
import com.info.zhiduoduo.wxsdk.utils.LogUtil;
import com.info.zhiduoduo.wxsdk.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信支付
 */
public class WxPayApiService {

	WXPayConfig wxPayConfig;
	WXPay wxPay;

	/**
	 * 根据不同的支付配置，创建支付api服务
	 *
	 * @param wxPayConfig
	 * @return
	 */
	public static WxPayApiService init(WXPayConfig wxPayConfig) {
		WxPayApiService service = new WxPayApiService();
		service.wxPayConfig = wxPayConfig;
		service.wxPay = new WXPay(wxPayConfig);
		return service;
	}

	//************************************** 微信支付 ************************************//

	/**
	 统一下单

	 @param data 数据
	  * @return 结果
	 */
	public WxUnifiedOrderResult unifiedOrder(WxUnifiedOrderData data) {

		String dataJson = JSON.toJSONString(data);

		HashMap<String, String> dataMap = JSON.parseObject(dataJson, new HashMap<String, String>().getClass());
		dataMap.put("trade_type", "JSAPI");

		//去掉空的字段
		Map<String, String> finalMap = dataMap.entrySet()
				.stream()
				.filter(entry -> !StringUtil.isEmpty(entry.getKey()) && !StringUtil.isEmpty(entry.getValue()))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
		LogUtil.info("签名的数据 =    " + finalMap.toString());
		Map<String, String> resultMap = unifiedOrder(finalMap);
		if (resultMap == null) {
			return null;
		}
		String resultJson = JSON.toJSONString(resultMap);
		LogUtil.info("微信下单返回结果:" + resultJson);
		return JSON.parseObject(resultJson, WxUnifiedOrderResult.class);
	}

	/**
	 统一下单

	 @param data 数据
	 @return 结果
	 */
	private Map<String, String> unifiedOrder(Map<String, String> data) {
		try {
			return wxPay.unifiedOrder(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 将统一下单成功后返回的数据生成签名,返回给前端

	 @param data
	 @return
	 @throws Exception
	 */
	public String generateSignature(Map<String, String> data) throws Exception {
		return WXPayUtil.generateSignature(data, wxPayConfig.getKey());
	}


	/**
	 检验微信支付成功后,通知服务器的数据的签名是否正确

	 @param notifyMap
	 @return
	 */
	public boolean isPayResultNotifySignatureValid(Map<String, String> notifyMap) {
		try {
			return wxPay.isPayResultNotifySignatureValid(notifyMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public Map<String, String> xmlToMap(String notifyData) throws Exception {
		return WXPayUtil.xmlToMap(notifyData);
	}

	public String mapToXml(Map<String, String> map) throws Exception {
		return WXPayUtil.mapToXml(map);
	}
}
